/*
 *  nkToPsiDelta.c
 *  AutoEllips
 *
 *  Created by Simon Martin on 27/05/2010.
 *  Copyright 2010 __MyCompanyName__. All rights reserved.
 *
 */

#include "nkToPsiDelta.h"

int nkToPsiDelta(WINDOW *mainwnd,ellipspar_t *ellipsparams)
{
// function to input n and k, thickness 

// outputs psi and delta
	double complex nf; // film refrative index
	double complex n1,n3; // capping and substrate refractive indices
	double angle; // ellipsometer angle
	double thick;// film thickness (Angstromms)
	double lamda;// light wavelength (Angstromms)
	double complex cos1,cos2,cos3; // cosines of angles in the media
	double complex rp12,rp23,rs12,rs23; // fresnel terms
	double complex Rs, Rp;
	double  psi;
	double  delta;
	double complex rho;
	double complex expt=0.;
	char* valueString;
	valueString=(char *)malloc(50*sizeof(char));
	
	
	
	mvprintw(1,1,"Input film n, k and thickness (Angstromms)");
	mvprintw(3,1,"nf?");
	
	refresh();
	echo();
	getstr(valueString);
	nf=atof(valueString); // sets real part
	
	mvprintw(5,1,"kf?:");
	
	refresh();
	echo();
	getstr(valueString);
	nf+=-I*atof(valueString);
	
	mvprintw(5,1,"thickness?:");
	
	refresh();
	echo();
	getstr(valueString);
	thick=atof(valueString);
	
	
	
	n1=1.0;
	n3=ellipsparams->ellipspar_values[1]+I*(ellipsparams->ellipspar_values[2]);
	
	// got input data now set up the calculations
	angle=degreesToRadians(ellipsparams->ellipspar_values[0]) ;
	cos1=ccos(angle);
	cos2=cos_snell(n1,nf,angle);
	
	cos3=cos_snell(n1,n3,angle);
	
	// now calculate the fresnel terms
	// rp
	rp12=rp(n1,nf,cos1,cos2);
	rp23=rp(nf,n3,cos2,cos3);
	//rs
	rs12=rs(n1,nf,cos1,cos2);
	rs23=rs(nf,n3,cos2,cos3);
	
	expt=cexp(-4.*I*M_PI*thick*nf*cos2/ellipsparams->ellipspar_values[5]);
	
	Rp=(rp12+rp23*expt)/(1.0+rp12*rp23*expt);
	Rs=(rs12+rs23*expt)/(1.0+rs12*rs23*expt);
	
	rho=Rp/Rs;
	
	delta=carg(rho)*180./M_PI;
	
	if ((creal(rho)<0.)&&(fabs(cimag(rho))<1.e-6)) {
		delta=M_PI;
	}
	
	psi=atan(cabs(rho))*180./M_PI;
	
	if (delta<0.) {
		delta=delta+M_2_PI;
	}
	
	printw("psi=%g,  delta=%g",psi,delta);
	refresh();
	getch();
	
	return(0);
	
}